package com.ruoyi.common.utils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 身份二要素认证
 */
public class PersonApi {

	private static final Logger log = LoggerFactory.getLogger(PersonApi.class);

	private static JsonParser jsonParser = new JsonParser();

/*	public static void main(String[] args) {
		boolean res = invokeShenfenJUHE("杨振伟", "420321199009012436");
		System.out.println(res);
//		boolean res = isDebit("6225887863208837");
		String allows = "ICBC,ABC,BOC,CCB";
//		System.out.println(res);
//		JsonObject res = checkCard("6225887863208837");
//		System.out.println(res);
//		if (res != null) {
//			JsonObject x = res.getAsJsonObject("result");
//			String ss = x.get("cardtype").toString().replaceAll("\"", "");
//			String abbreviation = x.get("abbreviation").toString().replaceAll("\"", "");
//			System.out.println(abbreviation);
//			if (ss.equals("贷记卡"))
//				System.out.println(1);
//		}
	}*/

	/**
	 * 判断是否为信用卡
	 * 
	 * @param bankcard
	 * @return
	 */
	public static boolean isCredit(String bankcard) {
		boolean re = false;
		JsonObject res = checkCard(bankcard);
		if (res != null) {
			JsonObject x = res.getAsJsonObject("result");
			String ss = x.get("cardtype").toString().replaceAll("\"", "");
			if (ss.equals("贷记卡"))
				re = true;
		}
		return re;
	}

	public static boolean isDebit(String bankcard, String allows) {
		boolean re = false;
		JsonObject res = checkCard(bankcard);
		if (res != null) {
			JsonObject x = res.getAsJsonObject("result");
			String ss = x.get("cardtype").toString().replaceAll("\"", "");
			String abbreviation = x.get("bankname").toString().replaceAll("\"", "");
			if (ss.equals("借记卡") && allows.contains(abbreviation))
				re = true;
		}
		return re;
	}

	public static JsonObject checkCard(String bankcard) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("appId", ApiConst.APP_KEY);
		params.put("appKey", ApiConst.APP_PASS);
		params.put("bankcard", bankcard);
		params.put("key", ApiConst.API_KEY_CARD_JUHE);
		String result = HttpUtilsInvoke.post(ApiConst.API_URL_CARD_JUHE, params);
		// 解析json,并返回结果
		return jsonParser.parse(result).getAsJsonObject();
	}

	public static JsonObject invokeShenfen(String name, String idNum) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("appId", ApiConst.APP_KEY);
		params.put("appKey", ApiConst.APP_PASS);
		params.put("name", name);
		params.put("idNum", idNum);
		String result = HttpUtilsInvoke.post(ApiConst.API_URL_SHENFEN, params);
		// 解析json,并返回结果
		return jsonParser.parse(result).getAsJsonObject();
	}

	public static boolean invokeShenfenJUHE(String name, String idNum) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("key", ApiConst.APP_KEY_IDCARD_JUHE);
		params.put("realname", name);
		params.put("idcard", idNum);
		String uorderid = UUID.randomUUID().toString().replaceAll("-", "");
		params.put("uorderid", uorderid);
		String sign = ApiConst.OPEN_ID_JUHE + ApiConst.APP_KEY_IDCARD_JUHE + idNum + name + uorderid;
		params.put("sign",MD5UtilInvoke.MD5Encode(sign));
		String result = HttpUtilsInvoke.post(ApiConst.API_URL_IDCARD_JUHE, params);
		boolean res = false;
		JsonObject jsonObject = jsonParser.parse(result).getAsJsonObject();
		if (jsonObject != null) {
			String reason = jsonObject.get("reason").getAsString();
			if ("成功".equals(reason.trim())) {
				JsonObject asJsonObject = jsonObject.get("result").getAsJsonObject();
				res = "1".equals(asJsonObject.get("res").getAsString());
			}
		}
		return res;
	}

	/**
	 * 验证银行卡信息是否一直
	 * 
	 * @param name
	 * @param idNum
	 * @param bankAccount
	 * @param linkPhone
	 * @return
	 */
	public static Object[] invokeBank(String name, String idNum, String bankAccount, String linkPhone) {
		boolean result = PersonApi.invokeBankJuhe(name, idNum, bankAccount, linkPhone);
		String res_ = String.format("聚合数据,姓名%s,身份证%s,卡号%s,电话%s,返回结果%s", name, idNum, bankAccount,
				linkPhone, result);
		String res_1 = "";
//		System.out.println(res_);
		if (!result) {
			Map<String, String> params = new HashMap<String, String>();
			params.put("appId", ApiConst.APP_KEY);
			params.put("appKey", ApiConst.APP_PASS);
			params.put("name", name);
			params.put("idNum", idNum);
			params.put("cardNo", bankAccount);
			params.put("mobile", linkPhone);
			String result__ = HttpUtilsInvoke.post(ApiConst.API_URL_BANK, params);
			JsonObject jsonObject = jsonParser.parse(result__).getAsJsonObject();
			String code = jsonObject.get("code").getAsString();
			if ("200000".equals(code)) {
				JsonObject asJsonObject = jsonObject.get("data").getAsJsonObject();
				String result_value = asJsonObject.get("result").getAsString();
				if ("01".equals(result_value.trim())) {
					result = true;
				}
			}
			res_1 = String.format("创蓝数据,姓名%s,身份证%s,卡号%s,电话%s,返回结果%s", name, idNum, bankAccount,
					linkPhone, result);

		}
		return new Object[] { result, res_ + ":" + res_1 };
	}

	/**
	 * 通过聚合接口验证四要素是否一致
	 * 
	 * @param name
	 * @param idNum
	 * @param bankAccount
	 * @param linkPhone
	 * @param type 验证卡的类型 0 储蓄卡  1信用卡
	 * @return
	 */
	public static boolean invokeBankJuhe(String name, String idNum, String bankAccount, String linkPhone, String type) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("key", ApiConst.APP_KEY_BANK_JUHE);
		params.put("realname", name);
		params.put("idcard", idNum);
		params.put("bankcard", bankAccount);
		params.put("mobile", linkPhone);
		params.put("type", type);
		params.put("uorderid", UUID.randomUUID().toString().replaceAll("-", ""));
		String sign = ApiConst.OPEN_ID_JUHE + ApiConst.APP_KEY_BANK_JUHE + bankAccount + name + idNum + linkPhone;
		params.put("sign", MD5UtilInvoke.MD5Encode(sign));
		String result = HttpUtilsInvoke.post(ApiConst.API_URL_BANK_JUHE, params);
		boolean res = false;
		JsonObject jsonObject = jsonParser.parse(result).getAsJsonObject();
		if (jsonObject != null) {
			String reason = jsonObject.get("reason").getAsString();
			if ("成功".equals(reason.trim())) {
				JsonObject asJsonObject = jsonObject.get("result").getAsJsonObject();
				res = "1".equals(asJsonObject.get("res").getAsString());
			}
		}
		return res;
	}
	
	/**
	 * 重载 不区分信用卡储蓄卡通过聚合接口验证四要素是否一致
	 * 
	 * @param name
	 * @param idNum
	 * @param bankAccount
	 * @param linkPhone
	 * @return
	 */
	public static boolean invokeBankJuhe(String name, String idNum, String bankAccount, String linkPhone) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("key", ApiConst.APP_KEY_BANK_JUHE);
		params.put("realname", name);
		params.put("idcard", idNum);
		params.put("bankcard", bankAccount);
		params.put("mobile", linkPhone);
		params.put("uorderid", UUID.randomUUID().toString().replaceAll("-", ""));
		String sign = ApiConst.OPEN_ID_JUHE + ApiConst.APP_KEY_BANK_JUHE + bankAccount + name + idNum + linkPhone;
		params.put("sign", MD5UtilInvoke.MD5Encode(sign));
		String result = HttpUtilsInvoke.post(ApiConst.API_URL_BANK_JUHE, params);
		boolean res = false;
		JsonObject jsonObject = jsonParser.parse(result).getAsJsonObject();
		if (jsonObject != null) {
			String reason = jsonObject.get("reason").getAsString();
			if ("成功".equals(reason.trim())) {
				JsonObject asJsonObject = jsonObject.get("result").getAsJsonObject();
				res = "1".equals(asJsonObject.get("res").getAsString());
			}
		}
		return res;
	}
	

	/**
	 * 身份证实名认证
	 * 
	 * @param name
	 * @param idNum
	 * @return
	 */
	public static boolean doinvokeShenfen(String name, String idNum) {
		// 先使用聚合数据进行验证，如果验证失败，则使用创蓝数据进行验证
		boolean result = PersonApi.invokeShenfenJUHE(name, idNum);
		String res_ = String.format("调用聚合数据实名认证请求参数:姓名%s,身份证%s,返回结果%s", name, idNum, result);
		System.out.println(res_);
		if (!result) {
			// 1.调用身份信息校验api
			final JsonObject jsonObject = PersonApi.invokeShenfen(name, idNum);
			// 2.处理返回结果
			if (jsonObject != null) {
				// 响应code码。200000：成功，其他失败
				String code = jsonObject.get("code").getAsString();
				if ("200000".equals(code)) {
					JsonObject jsonElement = jsonObject.get("data").getAsJsonObject();
					String result_ = jsonElement.get("result").getAsString();
					if (jsonElement != null && "01".equals(result_)) {
						result = true;
					}
				}
			}
			res_ = String.format("二次调用创蓝实名认证请求参数:姓名%s,身份证%s,返回结果%s", name, idNum, result);
			System.out.println(res_);
		}
		return result;
	}

	/**
	 * 扫描身份证接口
	 * 
	 * @param imgurl 身份证url
	 * @param fount  是否为正面身份证
	 * @return
	 */
	public static JsonObject doinvokeShenfenOCR(String imgurl, String ocrType) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("appId", ApiConst.APP_KEY);
		params.put("appKey", ApiConst.APP_PASS);
		// imageType为URL时，传入照片的网络URL地址, 支持jpg/png/bmp格式；
		// imageType为BASE64时，传入照片的base64字符编码，base64编码不包含data:image前缀，且图片大小不能大于2M
		params.put("image", imgurl);
		params.put("imageType", "URL"); // 图片类型（图片类型：URL或BASE64）
		params.put("ocrType", ocrType);// 正反面
		String result = HttpUtilsInvoke.post(ApiConst.API_URL_SHENFEN_OCR, params);
		// 解析json,并返回结果
		JsonParser jsonParser = new JsonParser();
		// 身份证正面{"chargeStatus":1,"message":"成功","data":{"tradeNo":"18111214401412407","code":"0","riskType":"normal","address":"湖北省浠水县散花镇涂墩村6组26号","birth":"19901224","name":"钱程","cardNum":"421125199012247936","sex":"男","nation":"汉"},"code":"200000"}
		return jsonParser.parse(result).getAsJsonObject();
	}

	public static Map<Integer, Object> doinvokeShenfenOCRBoolean(JsonObject doinvokeShenfenOCR, String ocrType) {
		// 身份证正面{"chargeStatus":1,"message":"成功","data":{"tradeNo":"18111214401412407","code":"0","riskType":"normal","address":"湖北省浠水县散花镇涂墩村6组26号","birth":"19901224","name":"钱程","cardNum":"421125199012247936","sex":"男","nation":"汉"},"code":"200000"}
		Map<Integer, Object> result = new HashMap<>();
		if (doinvokeShenfenOCR != null) {
			// 响应code码。200000：成功，其他失败
			String code = doinvokeShenfenOCR.get("code").getAsString();
			if ("200000".equals(code) && doinvokeShenfenOCR.get("data") != null) {
				JsonObject asJsonObject = doinvokeShenfenOCR.get("data").getAsJsonObject();
				if ("0".equals(ocrType)) {
					JsonElement jsonElement = asJsonObject.get("cardNum");
					if (jsonElement != null && jsonElement.toString().length() > 2) {
						result.put(1, true);
					} else {
						result.put(1, false);
					}
				} else {
					JsonElement issuingDate = asJsonObject.get("issuingDate");// 有效期开始时间
					JsonElement expiryDate = asJsonObject.get("expiryDate");// 有效期截止时间
					JsonElement issuingAuthority = asJsonObject.get("issuingAuthority");// 签发机关
					boolean issuingDate_B = (issuingDate != null && issuingDate.toString().length() > 2);
					boolean expiryDate_B = (expiryDate != null && expiryDate.toString().length() > 2);
					boolean issuingAuthority_B = (issuingAuthority != null && issuingAuthority.toString().length() > 2);
					if (expiryDate_B) {
						try {
							Date parse = new SimpleDateFormat("yyyymmdd")
									.parse(expiryDate.toString().replaceAll("\"", ""));
							boolean expire = new Date().getTime() - parse.getTime() > 0;
							if (expire) {
								result.put(1, false);
								result.put(2, "身份证已过期");
							} else {
								result.put(1, true);
							}
						} catch (ParseException e) {
						}
					} else if (issuingDate_B || expiryDate_B || issuingAuthority_B) {
						result.put(1, true);
					} else {
						result.put(1, false);
					}
				}
			} else {
				result.put(1, false);
			}
		} else {
			result.put(1, false);
		}
		return result;
	}

}
